from flask import Blueprint, render_template, request, redirect, url_for, session, flash

from models import CardModel
from .forms import LoginForm

auth_dp = Blueprint('auth', __name__, url_prefix='/auth')

# 定义管理员凭证（实际应用中应从配置加载）
ADMIN_CARD_ID = "123456"
ADMIN_PASSWORD = "888888"


@auth_dp.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    # 获取表单数据
    cardID = request.form.get('cardID', '').strip()
    passwd = request.form.get('passwd', '')

    # 管理员登录检查（使用正确的逻辑和类型）
    if cardID == ADMIN_CARD_ID and passwd == ADMIN_PASSWORD:
        # 设置管理员会话标志
        session['is_admin'] = True
        session['cardID'] = cardID
        return redirect(url_for('admin.adminmain'))

    # 客户登录检查
    card = CardModel.query.filter_by(cardID=cardID).first()

    if not card:
        flash('银行卡不存在', 'error')
    elif card.passwd != passwd:
        flash('密码错误', 'error')
    elif card.IsReportLoss == '是':
        flash('该卡已被挂失', 'error')
    else:
        # 设置客户会话
        session['is_admin'] = False
        session['cardID'] = cardID
        flash('登录成功', 'success')
        return redirect(url_for('client.clientmain'))

    # 如果有错误，返回登录页面
    return redirect(url_for('auth.login'))
@auth_dp.route('/clear-error', methods=['POST'])
def clear_error():
    session.pop('login_error', None)
    return '', 204

'''
@admin_bp.route('/adminmain', methods=['GET', 'POST'])
def adminmain():
    # 这里可以添加管理员仪表板逻辑
    if not session.get('is_admin'):
        flash('无权访问管理员界面', 'error')
        return redirect(url_for('auth.login'))
'''


@auth_dp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('auth.login'))